<?php

namespace app\admin\model;

use app\common\enums\StatusEnum;
use app\common\service\Oss;
use app\common\service\Mts;
use think\Db;
use app\api\model\LangClassVideoTransfer AS LangClassVideoTransferModel;

class LangClassFile extends \app\common\model\LangClassFile
{
    /**
     * 文件列表
     * @param $classId
     * @param $courseType
     * @param $type
     * @param array $where
     * @return array
     * @throws \think\exception\DbException
     */
    public static function getList($classId, $courseType, $type, $where = [])
    {
        $sql = static::field('id, class_id, course_type, type, file, file_name, is_free, sort_num, status, create_time, update_time')
            ->where(['class_id' => $classId, 'course_type' => $courseType, 'type' => $type]);

        if ($where) {
            $sql->where($where);
        }

        $data = $sql->paginate(null, false, ['query' => request()->param()]);

        $fileIds = [];
        foreach ($data->items() as $key => $value) {
            $fileIds[$value['id']] = $value['id'];
        }

        $count = [];
        if ($type == self::TYPE_CLASS_FILE || $type == self::TYPE_HOMEWORK) {
            if ($fileIds) {
                $count = DownloadLog::getColumn($fileIds);
            }
        }

        $model = $data->each(function ($item, $key) use ($count) {
            $item['count'] = isset($count[$item['id']]) ? $count[$item['id']] : 0;
            $item['is_free'] = self::attributes('is_free', $item['is_free']);
            $item['create_time'] = get_datetime($item['create_time']);
            $item['update_time'] = get_datetime($item['update_time']);
            $item['statusText'] = StatusEnum::getStatus($item['status']);
            return $item;
        });

        // 获取总记录数
        $count = $model->total();
        return [
            'model' => $model,
            'count' => $count
        ];
    }

    /**
     * 添加修改文件
     * @param $data
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function saveOne($data)
    {
        $saveData = [
            'class_id' => $data['class_id'],
            'course_type' => $data['course_type'],
            'type' => $data['type'],
            'file' => $data['file'],
            'file_name' => $data['file_name'],
            'description' => isset($data['description']) ? $data['description'] : '',
            'is_free' => isset($data['is_free']) ? $data['is_free'] : self::FREE_NO,
            'sort_num' => $data['sort_num'],
            'status' => $data['status'],
            'update_time' => time()
        ];
        $log = [];
        $videoImg = '';
        $download = true;
        if (isset($data['id']) && $data['id'] > 0) {
            $log = static::get($data['id']);
            if (!empty($log) && $log['file'] == $data['file']) {
                $download = false;
                $videoImg = $log['video_img'];
            }
        }

        if ($download === true && $data['type'] == self::TYPE_VIDEO) {
            // 视频就截取第一帧下载到本地，再上传到oss
            $downloadFile = get_video_img(config('file_prefix') . $data['file']);
            $saveFile = download_file($downloadFile, './download/', '.jpg');
            if ($saveFile !== false) {
                $videoImg = 'lang_class_file/' . $saveFile['filename'];
                $oss = new Oss();
                $oss->upload($videoImg, $saveFile['filePath']);
            }
        }

        $saveData['video_img'] = $videoImg;

        if ($log) {
            Db::name('lang_class_file')
                ->where('id', $data['id'])
                ->data($saveData)
                ->update();
            $id = $data['id'];
        } else {
            $saveData['create_time'] = time();
            $id = Db::name('lang_class_file')->insertGetId($saveData);

        }

        if ($download === true && $data['type'] == self::TYPE_VIDEO) {

            $fileName = basename($data['file']);
            $info = pathinfo($fileName);
            $tem = config('video_transfer_tem');
            $s = new Mts();
            
            $d['file'] = $data['file'];
            $d['create_time'] = time();
            for ($i=1; $i < 4 ; $i++) { 
                $record = LangClassVideoTransferModel::getRecordByFile($data['file'],$i);
                if(empty($record)){
                    if($i == 1){
                        $key = "high";
                    }else if($i == 1){
                        $key = "normal";
                    }else if($i == 2){
                        $key = "general";
                    }
                    $rs = $s->transfer($data['file'],"lang_file_transfer/".$info['filename']."-".$i.".".$info['extension'],$tem[$key]);
                    //print_r($rs);exit();
                    if ($rs['code'] ==0){
                        $d['job_id'] = $rs['data'];
                        $d['transter_file'] = "lang_file_transfer/".$info['filename']."-".$i.".".$info['extension'];
                        $d['type'] = $i;
                        Db::name('lang_class_video_transfer')->insert($d);
                    }
                }
            }
            
        }

        return $id;
    }

    /**
     * 批量禁用启用
     * @param $ids
     * @param $status
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function disables($ids, $status)
    {
        static::where('id', 'in', $ids)->update(['status' => $status]);
    }
    
    
    
   
}